<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Java8流处理 | yili的个人小站</title><meta name="keywords" content="Java8"><meta name="author" content="yili"><meta name="copyright" content="yili"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="Stream流的介绍在Java8中新增加了一个十分简化的操作：Stream 可以使用一种较为方便的方式来对集合中的数据进行处理。所以Stream也被称之为高级迭代器。 流的顺序是不可改变的： filter–&gt;map–&gt;limit–&gt;collect  外部迭代和内部迭代： 外部迭代就是使用for-each来对数据进行处理，在一个for循环中对数据进行处理，其在底层使用的是迭代器的语">
<meta property="og:type" content="article">
<meta property="og:title" content="Java8流处理">
<meta property="og:url" content="https://yili979.gitee.io/blog/2021/10/05/java/Java8%E6%B5%81%E5%A4%84%E7%90%86/index.html">
<meta property="og:site_name" content="yili的个人小站">
<meta property="og:description" content="Stream流的介绍在Java8中新增加了一个十分简化的操作：Stream 可以使用一种较为方便的方式来对集合中的数据进行处理。所以Stream也被称之为高级迭代器。 流的顺序是不可改变的： filter–&gt;map–&gt;limit–&gt;collect  外部迭代和内部迭代： 外部迭代就是使用for-each来对数据进行处理，在一个for循环中对数据进行处理，其在底层使用的是迭代器的语">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://i.loli.net/2021/10/04/7PWqmtGLMs3hign.jpg">
<meta property="article:published_time" content="2021-10-04T16:03:45.000Z">
<meta property="article:modified_time" content="2021-10-05T06:55:27.582Z">
<meta property="article:author" content="yili">
<meta property="article:tag" content="Java8">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://i.loli.net/2021/10/04/7PWqmtGLMs3hign.jpg"><link rel="shortcut icon" href="/blog/img/favicon.ico"><link rel="canonical" href="https://yili979.gitee.io/blog/2021/10/05/java/Java8%E6%B5%81%E5%A4%84%E7%90%86/"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/blog/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/blog/',
  algolia: undefined,
  localSearch: undefined,
  translate: undefined,
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: {"chs_to_cht":"你已切换为繁体","cht_to_chs":"你已切换为简体","day_to_night":"你已切换为深色模式","night_to_day":"你已切换为浅色模式","bgLight":"#49b1f5","bgDark":"#121212","position":"bottom-left"},
  source: {
    jQuery: 'https://cdn.jsdelivr.net/npm/jquery@latest/dist/jquery.min.js',
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/js/jquery.justifiedGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/css/justifiedGallery.min.css'
    },
    fancybox: {
      js: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.js',
      css: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: false,
  isanchor: true
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'Java8流处理',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2021-10-05 14:55:27'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const fontSizeVal = saveToLocal.get('global-font-size')
    if (fontSizeVal !== undefined) {
      document.documentElement.style.setProperty('--global-font-size', fontSizeVal + 'px')
    }
    
    const detectApple = () => {
      if (GLOBAL_CONFIG_SITE.isHome && /iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><link rel="stylesheet" href="/blog/css/custom.css" media="defer" onload="this.media='all'"><meta name="generator" content="Hexo 5.4.0"></head><body><div id="loading-box"><div class="loading-left-bg"></div><div class="loading-right-bg"></div><div class="spinner-box"><div class="configure-border-1"><div class="configure-core"></div></div><div class="configure-border-2"><div class="configure-core"></div></div><div class="loading-word">加载中...</div></div></div><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src="https://i.loli.net/2021/10/05/BKpC6sFEo5Dl7qA.jpg" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="site-data"><div class="data-item is-center"><div class="data-item-link"><a href="/blog/archives/"><div class="headline">文章</div><div class="length-num">28</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/blog/tags/"><div class="headline">标签</div><div class="length-num">20</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/blog/categories/"><div class="headline">分类</div><div class="length-num">13</div></a></div></div></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/blog/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/blog/archives/"><i class="fa-fw fas fa-archive"></i><span> 时间轴</span></a></div><div class="menus_item"><a class="site-page" href="/blog/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/blog/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/blog/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/blog/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('https://i.loli.net/2021/10/04/7PWqmtGLMs3hign.jpg')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/blog/">yili的个人小站</a></span><div id="menus"><div class="menus_items"><div class="menus_item"><a class="site-page" href="/blog/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/blog/archives/"><i class="fa-fw fas fa-archive"></i><span> 时间轴</span></a></div><div class="menus_item"><a class="site-page" href="/blog/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/blog/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/blog/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/blog/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">Java8流处理</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2021-10-04T16:03:45.000Z" title="发表于 2021-10-05 00:03:45">2021-10-05</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2021-10-05T06:55:27.582Z" title="更新于 2021-10-05 14:55:27">2021-10-05</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/blog/categories/Java-8/">Java 8</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">971</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>4分钟</span></span><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="Java8流处理"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h1 id="Stream"><a href="#Stream" class="headerlink" title="Stream"></a>Stream</h1><h3 id="流的介绍"><a href="#流的介绍" class="headerlink" title="流的介绍"></a>流的介绍</h3><p>在Java8中新增加了一个十分简化的操作：Stream</p>
<p>可以使用一种较为方便的方式来对集合中的数据进行处理。所以Stream也被称之为高级迭代器。</p>
<p>流的顺序是不可改变的：</p>
<p>filter–&gt;map–&gt;limit–&gt;collect</p>
<p><img src="https://i.loli.net/2021/10/05/4C28D7xScMgd5Ak.png" alt="image-20210923150547670"></p>
<p><strong>外部迭代和内部迭代</strong>：</p>
<p>外部迭代就是使用for-each来对数据进行处理，在一个for循环中对数据进行处理，其在底层使用的是迭代器的语法糖模式。</p>
<p>内部迭代是通过map，filter，collect等流操作来对数据进行处理。</p>
<p><img src="https://i.loli.net/2021/10/05/G92cD3tHNfgXRLV.png" alt="image-20210923150915343"></p>
<h3 id="流的处理"><a href="#流的处理" class="headerlink" title="流的处理"></a>流的处理</h3><p><img src="https://i.loli.net/2021/10/05/XkdugTqYn7LAQOU.png" alt="image-20210923150952270"></p>
<p>使用流包括三个操作：</p>
<ul>
<li>对数据源进行查询操作</li>
<li>中间链式操作</li>
<li>终端操作</li>
</ul>
<p><img src="https://i.loli.net/2021/10/05/TxGJM5Wv7FQ1omP.png" alt="image-20210923151131450"></p>
<h3 id="使用流"><a href="#使用流" class="headerlink" title="使用流"></a>使用流</h3><h4 id="筛选和切片"><a href="#筛选和切片" class="headerlink" title="筛选和切片"></a>筛选和切片</h4><p><strong>1.distinct</strong>：将相同的数据进行筛选</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">FilterTest</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        List&lt;Integer&gt; list = Arrays.asList(<span class="number">1</span>, <span class="number">2</span>, <span class="number">4</span>, <span class="number">5</span>, <span class="number">6</span>, <span class="number">7</span>);</span><br><span class="line">        list.stream()</span><br><span class="line">                .filter(integer -&gt; integer%<span class="number">2</span>==<span class="number">0</span>)</span><br><span class="line">                .distinct()</span><br><span class="line">                <span class="comment">//筛选相同的元素</span></span><br><span class="line">                .forEach(System.out::println);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><strong>2.limit</strong> 截取对应数字的元素</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">FilterTest</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        List&lt;Integer&gt; list = Arrays.asList(<span class="number">1</span>, <span class="number">2</span>, <span class="number">4</span>, <span class="number">5</span>, <span class="number">6</span>, <span class="number">7</span>);</span><br><span class="line">        list.stream()</span><br><span class="line">                .filter(integer -&gt; integer&gt;<span class="number">2</span>)</span><br><span class="line">                .limit(<span class="number">2</span>)</span><br><span class="line">                <span class="comment">//筛选相同的元素</span></span><br><span class="line">                .forEach(System.out::println);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="number">4</span></span><br><span class="line"><span class="number">5</span></span><br></pre></td></tr></table></figure>

<p><strong>3.skip</strong>：跳过对应数量的元素</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">FilterTest</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        List&lt;Integer&gt; list = Arrays.asList(<span class="number">1</span>, <span class="number">2</span>, <span class="number">4</span>, <span class="number">5</span>, <span class="number">6</span>, <span class="number">7</span>);</span><br><span class="line">        list.stream()</span><br><span class="line">                .filter(integer -&gt; integer&gt;<span class="number">2</span>)</span><br><span class="line">                .skip(<span class="number">2</span>)</span><br><span class="line">                <span class="comment">//筛选相同的元素</span></span><br><span class="line">                .forEach(System.out::println);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="number">6</span></span><br><span class="line"><span class="number">7</span></span><br></pre></td></tr></table></figure>

<h4 id="映射"><a href="#映射" class="headerlink" title="映射"></a>映射</h4><p>对流中的每个元素进行修改</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MapTest</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        List&lt;String&gt; list = Arrays.asList(<span class="string">&quot;Java 8&quot;</span>, <span class="string">&quot;Lambdas&quot;</span>, <span class="string">&quot;In&quot;</span>, <span class="string">&quot;Action&quot;</span>);</span><br><span class="line">        List&lt;String&gt; collect = list.stream()</span><br><span class="line">                .map(String::toLowerCase)</span><br><span class="line">                .collect(Collectors.toList());</span><br><span class="line">        System.out.println(collect);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>扁平化处理，可以将多个流转化为一个单一的流</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">String[] words = &#123;<span class="string">&quot;GoodBye&quot;</span>,<span class="string">&quot;World&quot;</span>&#125;;</span><br><span class="line">List&lt;String&gt; stringList = Arrays.stream(words)</span><br><span class="line">        .map(word -&gt; word.split(<span class="string">&quot;&quot;</span>))</span><br><span class="line">        .flatMap(Arrays::stream)</span><br><span class="line">        .distinct()</span><br><span class="line">        .collect(Collectors.toList());</span><br><span class="line"><span class="keyword">for</span> (String s : stringList) &#123;</span><br><span class="line">    System.out.println(s);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="匹配"><a href="#匹配" class="headerlink" title="匹配"></a>匹配</h4><p>检查流中的元素是否都满足系列条件</p>
<p>有下列方法可以使用：</p>
<p>Stream  API通过allMatch、anyMatch、noneMatch、findFirst和findAny方法提供了这样的工具。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">List&lt;Integer&gt; someNumbers = Arrays.asList(<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>, <span class="number">5</span>); </span><br><span class="line">Optional&lt;Integer&gt; firstSquareDivisibleByThree = </span><br><span class="line"> someNumbers.stream() </span><br><span class="line"> .map(x -&gt; x * x) </span><br><span class="line"> .filter(x -&gt; x % <span class="number">3</span> == <span class="number">0</span>) </span><br><span class="line"> .findFirst(); <span class="comment">// 9 </span></span><br></pre></td></tr></table></figure>

<h3 id="流的收集"><a href="#流的收集" class="headerlink" title="流的收集"></a>流的收集</h3><h4 id="收集"><a href="#收集" class="headerlink" title="收集"></a>收集</h4><p>将一个流转化为一个流的形式：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">List&lt;String&gt; stringList = Arrays.stream(words)</span><br><span class="line">        .map(word -&gt; word.split(<span class="string">&quot;&quot;</span>))</span><br><span class="line">        .flatMap(Arrays::stream)</span><br><span class="line">        .distinct()</span><br><span class="line">        .collect(Collectors.toList());</span><br></pre></td></tr></table></figure>

<p>最基础的收集就是使用</p>
<p>counting来对流中的数目来进行计算</p>
<p>long howManyDishes = menu.stream().collect(Collectors.counting()); </p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//使用minBy来计算最小值</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">static</span> &lt;T&gt; Collector&lt;T, ?, Optional&lt;T&gt;&gt;</span><br><span class="line">minBy(Comparator&lt;? <span class="keyword">super</span> T&gt; comparator) &#123;</span><br><span class="line">    <span class="keyword">return</span> reducing(BinaryOperator.minBy(comparator));</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">//使用maxBy来计算最大值</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">static</span> &lt;T&gt; Collector&lt;T, ?, Optional&lt;T&gt;&gt;</span><br><span class="line">maxBy(Comparator&lt;? <span class="keyword">super</span> T&gt; comparator) &#123;</span><br><span class="line">    <span class="keyword">return</span> reducing(BinaryOperator.maxBy(comparator));</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">//使用sumingInt来计算总数</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">static</span> &lt;T&gt; Collector&lt;T, ?, Integer&gt;</span><br><span class="line">    summingInt(ToIntFunction&lt;? <span class="keyword">super</span> T&gt; mapper) &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">new</span> CollectorImpl&lt;&gt;(</span><br><span class="line">        () -&gt; <span class="keyword">new</span> <span class="keyword">int</span>[<span class="number">1</span>],</span><br><span class="line">        (a, t) -&gt; &#123; a[<span class="number">0</span>] += mapper.applyAsInt(t); &#125;,</span><br><span class="line">        (a, b) -&gt; &#123; a[<span class="number">0</span>] += b[<span class="number">0</span>]; <span class="keyword">return</span> a; &#125;,</span><br><span class="line">        a -&gt; a[<span class="number">0</span>], CH_NOID);</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">//使用averagingInt来对数据统计平均值信息</span></span><br><span class="line">Double collect = transactions.stream()</span><br><span class="line">    .collect(Collectors.averagingInt(Transaction::getValue));</span><br><span class="line">System.out.println(collect);</span><br></pre></td></tr></table></figure>

<h4 id="分组处理"><a href="#分组处理" class="headerlink" title="分组处理"></a>分组处理</h4><p>分组处理将不同的数据分割到不同的value中。</p>
<p>和在数据库中对数据进行分组操作是十分相似的，所以使用</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">Map&lt;Integer, List&lt;Transaction&gt;&gt; map = transactions.stream()</span><br><span class="line">        .collect(Collectors.groupingBy(Transaction::getYear));</span><br></pre></td></tr></table></figure>

<h4 id="分区处理"><a href="#分区处理" class="headerlink" title="分区处理"></a>分区处理</h4><p>分区处理和分组处理十分相似，不过是直接使用布尔类型的值来进行处理，比如需要将满足条件和不满足条件的值分割开来。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> Map&lt;Boolean, List&lt;Integer&gt;&gt; partitionPrimes(<span class="keyword">int</span> n) &#123; </span><br><span class="line"> 	<span class="keyword">return</span> IntStream.rangeClosed(<span class="number">2</span>, n).boxed() </span><br><span class="line"> 		.collect( </span><br><span class="line">		 partitioningBy(candidate -&gt; isPrime(candidate))); </span><br><span class="line">&#125; </span><br></pre></td></tr></table></figure>

<p>以上是使用分区处理来得到一个Map</p>
<h4 id="Collectors的工厂方法"><a href="#Collectors的工厂方法" class="headerlink" title="Collectors的工厂方法"></a>Collectors的工厂方法</h4><p><img src="https://i.loli.net/2021/10/05/pdg4I86HVEaGYMQ.png" alt="image-20210923204452824"></p>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="mailto:undefined">yili</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://yili979.gitee.io/blog/2021/10/05/java/Java8%E6%B5%81%E5%A4%84%E7%90%86/">https://yili979.gitee.io/blog/2021/10/05/java/Java8%E6%B5%81%E5%A4%84%E7%90%86/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://yili979.gitee.io/blog" target="_blank">yili的个人小站</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/blog/tags/Java8/">Java8</a></div><div class="post_share"><div class="social-share" data-image="https://i.loli.net/2021/10/04/7PWqmtGLMs3hign.jpg" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/social-share.js/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/social-share.js/dist/js/social-share.min.js" defer></script></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/blog/2021/10/05/nosql/Redis%E5%9F%BA%E7%A1%80/"><img class="prev-cover" src="https://i.loli.net/2021/10/04/R5mOBnMaeyZ7cpT.png" onerror="onerror=null;src='/blog/img/404.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">Redis基础</div></div></a></div><div class="next-post pull-right"><a href="/blog/2021/10/04/nosql/MongoDB%E7%9A%84CURD/"><img class="next-cover" src="https://images.pexels.com/photos/844297/pexels-photo-844297.jpeg?auto=compress&amp;cs=tinysrgb&amp;dpr=2&amp;h=650&amp;w=940" onerror="onerror=null;src='/blog/img/404.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">MongoDB的CURD</div></div></a></div></nav></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src="https://i.loli.net/2021/10/05/BKpC6sFEo5Dl7qA.jpg" onerror="this.onerror=null;this.src='/blog/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">yili</div><div class="author-info__description">身骑白马</div></div><div class="card-info-data"><div class="card-info-data-item is-center"><a href="/blog/archives/"><div class="headline">文章</div><div class="length-num">28</div></a></div><div class="card-info-data-item is-center"><a href="/blog/tags/"><div class="headline">标签</div><div class="length-num">20</div></a></div><div class="card-info-data-item is-center"><a href="/blog/categories/"><div class="headline">分类</div><div class="length-num">13</div></a></div></div><a class="button--animated" id="card-info-btn" target="_blank" rel="noopener" href="https://github.com/qiuyuyin"><i class="fab fa-github"></i><span>github🍟</span></a></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn card-announcement-animation"></i><span>公告</span></div><div class="announcement_content">啦啦啦，写的不好还请见谅😉<div class="twopeople"><div class="twopeople"><div class="container"style="height:200px;"><canvas class="illo"width="800"height="800"style="max-width: 200px; max-height: 200px; touch-action: none; width: 640px; height: 640px;"></canvas></div><script src="js/twopeople1.js"></script><script src="js/zdog.dist.js"></script><script id="rendered-js"src="js/twopeople.js"></script><style>.twopeople{margin:0;align-items:center;justify-content:center;text-align:center}canvas{display:block;margin:0 auto;cursor:move}</style></div></div></div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#Stream"><span class="toc-text">Stream</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%B5%81%E7%9A%84%E4%BB%8B%E7%BB%8D"><span class="toc-text">流的介绍</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%B5%81%E7%9A%84%E5%A4%84%E7%90%86"><span class="toc-text">流的处理</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%BD%BF%E7%94%A8%E6%B5%81"><span class="toc-text">使用流</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E7%AD%9B%E9%80%89%E5%92%8C%E5%88%87%E7%89%87"><span class="toc-text">筛选和切片</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%98%A0%E5%B0%84"><span class="toc-text">映射</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%8C%B9%E9%85%8D"><span class="toc-text">匹配</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%B5%81%E7%9A%84%E6%94%B6%E9%9B%86"><span class="toc-text">流的收集</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%94%B6%E9%9B%86"><span class="toc-text">收集</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%88%86%E7%BB%84%E5%A4%84%E7%90%86"><span class="toc-text">分组处理</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%88%86%E5%8C%BA%E5%A4%84%E7%90%86"><span class="toc-text">分区处理</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#Collectors%E7%9A%84%E5%B7%A5%E5%8E%82%E6%96%B9%E6%B3%95"><span class="toc-text">Collectors的工厂方法</span></a></li></ol></li></ol></li></ol></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/blog/2022/03/08/something-about-crypto/" title="something about crypto"><img src="https://yili979.oss-cn-beijing.aliyuncs.com/img/image-20220124000713258.png" onerror="this.onerror=null;this.src='/blog/img/404.jpg'" alt="something about crypto"/></a><div class="content"><a class="title" href="/blog/2022/03/08/something-about-crypto/" title="something about crypto">something about crypto</a><time datetime="2022-03-08T12:01:13.000Z" title="发表于 2022-03-08 20:01:13">2022-03-08</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/blog/2022/03/08/golang%E5%86%85%E5%AD%98%E7%AE%A1%E7%90%86/" title="golang内存管理"><img src="https://yili979.oss-cn-beijing.aliyuncs.com/img/202203081958270.png" onerror="this.onerror=null;this.src='/blog/img/404.jpg'" alt="golang内存管理"/></a><div class="content"><a class="title" href="/blog/2022/03/08/golang%E5%86%85%E5%AD%98%E7%AE%A1%E7%90%86/" title="golang内存管理">golang内存管理</a><time datetime="2022-03-08T11:55:30.000Z" title="发表于 2022-03-08 19:55:30">2022-03-08</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/blog/2022/03/08/%E9%89%B4%E6%9D%83%E7%B3%BB%E7%BB%9F/" title="鉴权系统"><img src="https://yili979.oss-cn-beijing.aliyuncs.com/img/202203081950401.jpeg" onerror="this.onerror=null;this.src='/blog/img/404.jpg'" alt="鉴权系统"/></a><div class="content"><a class="title" href="/blog/2022/03/08/%E9%89%B4%E6%9D%83%E7%B3%BB%E7%BB%9F/" title="鉴权系统">鉴权系统</a><time datetime="2022-03-08T11:49:53.000Z" title="发表于 2022-03-08 19:49:53">2022-03-08</time></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2020 - 2022 By yili</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="font-plus" type="button" title="放大字体"><i class="fas fa-plus"></i></button><button id="font-minus" type="button" title="缩小字体"><i class="fas fa-minus"></i></button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div><script src="/blog/js/utils.js"></script><script src="/blog/js/main.js"></script><script src="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.js"></script><script>var preloader = {
  endLoading: () => {
    document.body.style.overflow = 'auto';
    document.getElementById('loading-box').classList.add("loaded")
  },
  initLoading: () => {
    document.body.style.overflow = '';
    document.getElementById('loading-box').classList.remove("loaded")

  }
}
window.addEventListener('load',preloader.endLoading())</script><div class="js-pjax"></div><script defer="defer" id="fluttering_ribbon" mobile="false" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/canvas-fluttering-ribbon.min.js"></script><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div></body></html>